package com.hwj.service.Impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hwj.entity.PostType;
import com.hwj.exception.CustomAuthException;
import com.hwj.mapper.PostTypeMapper;
import com.hwj.service.PostTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class PostTypeServiceImpl implements PostTypeService {
    @Autowired
    PostTypeMapper postTypeMapper;
    @Override
    public List<PostType> select() {
        return postTypeMapper.select();
    }

    @Override
    public int deleteByPrimaryKey(Long id) {
        return postTypeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(PostType record) {
        return postTypeMapper.insert(record);
    }

    @Override
    public int insertSelective(PostType record) {
        return postTypeMapper.insertSelective(record);
    }

    @Override
    public PostType selectByPrimaryKey(Long id) {
        return postTypeMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(PostType record) {
        return postTypeMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(PostType record) {
        return postTypeMapper.updateByPrimaryKey(record);
    }

    /*
    * 更新或者插入
    * */
    @Override
    public int updateAndInsert(PostType postType) {
        //转换成Optional避免空指针异常
        Optional<PostType> optionalPostType=Optional.ofNullable(postType);
        PostType postTypeNonNuLL = optionalPostType.orElseThrow(CustomAuthException::new);
        //获取是update还是Insert的选择,并作出分支
        int i=0;//该数用于表示插入成功或更新成功（成功1，失败0）
        try{
            if(postTypeNonNuLL.getPostTypeId()!=null){
                i=postTypeMapper.updateByPrimaryKeySelective(postTypeNonNuLL);
            }else{
                i= postTypeMapper.insertSelective(postTypeNonNuLL);
            }
        }catch (Exception e){
            throw new CustomAuthException("数据有误，请重新提交");
        }
        return i;
    }

    @Override
    public PageInfo<PostType> selectByPage(Integer pageNum, Integer pageSize, String postTypeName) {
        if(postTypeName!=null){
            postTypeName="%"+postTypeName+"%";
        }
        PageHelper.startPage(pageNum,pageSize);
        List<PostType> page=postTypeMapper.selectByPage(postTypeName);
        return new PageInfo<>(page);
    }
}
